//
//  KLoginViewController.m
//  Keping
//
//  Created by 柯平 on 2017/6/20.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KLoginViewController.h"
#import "KTabBarController.h"
#import "KRegisterViewController.h"
#import "KForgotViewController.h"
#import "KLoginRequest.h"
#import "KUserData.h"
#import "UIView+KP.h"
#import "KEaseMobManager.h"

@interface KLoginViewController ()

@property(nonatomic,strong)UIImageView* backgroundView;
@property(nonatomic,strong)UILabel* loginLabel;
@property(nonatomic,strong)UITextField* accountTf;
@property(nonatomic,strong)UIView* accLine;
@property(nonatomic,strong)UIView* pasLine;
@property(nonatomic,strong)UITextField* passwordTf;
@property(nonatomic,strong)UIButton* loginButton;
@property(nonatomic,strong)UIButton* rememberButton;
@property(nonatomic,strong)UILabel* rememberText;
@property(nonatomic,strong)UIButton* registerButton;
@property(nonatomic,strong)UIButton* forgetButton;

@end

@implementation KLoginViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.rememberButton.selected = [KAppConfig sharedConfig].isRememberPassword;
    self.accountTf.text = [KAppConfig sharedConfig].phone;//@"15521277218"
    if ([KAppConfig sharedConfig].rememberPassword) {
        self.passwordTf.text = [KAppConfig sharedConfig].password;//@"123456";
    }else{
        self.passwordTf.text = nil;
    }
}

#pragma mark - Method
-(void)loginAction{
    if (![self.accountTf.text isNotBlank]) {
        [self showErrorText:@"Please enter your phone/email."];
        return;
    }
    if (![self.passwordTf.text isNotBlank]) {
        [self showErrorText:@"Please enter password."];
        return;
    }
    [self showLoading:@"Wait..."];
    NSString* account = self.accountTf.text;
    NSString* password = [self.passwordTf.text md5String];
    KLoginRequest* loginRequest = [KLoginRequest new];
    WEAKSELF
    loginRequest.params = [NSDictionary dictionaryWithObjectsAndKeys:account,@"phone",password,@"passWord", nil];
    [loginRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        //type1
        KUserData* userData = [KUserData modelWithJSON:request.responseData];
        if (userData.statusCode == 200) {
            [[KAppConfig sharedConfig] setPhone:self.accountTf.text];
            [[KAppConfig sharedConfig] setLogined:YES];
            [[KAppConfig sharedConfig] setSessionId:[NSString stringWithFormat:@"JSESSIONID=%@",userData.sid]];
            [[KAppConfig sharedConfig] setVeritify:userData.partyView.identityAuthentication];
            [[KAppConfig sharedConfig] setCommunityId:userData.partyView.communityId];
            [[KAppConfig sharedConfig] setCommunityName:userData.partyView.communityName];
            [[KAppConfig sharedConfig] setUid:userData.partyView.uid];
            [[KAppConfig sharedConfig] setUserId:userData.partyView.uid];
            if ([KAppConfig sharedConfig].rememberPassword) {
                [KAppConfig sharedConfig].password = weakSelf.passwordTf.text;
            }
            if (![userData.partyView archive]) {
                KLog(@"保存用户信息失败！");
            }
            
            [KEaseMobManager easeMobLoginUsername:account password:password controller:self];
            //self.app.window.rootViewController = [KTabBarController new];
        }else{
            [weakSelf showErrorText:userData.msg errCode:userData.statusCode];
        }

    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

-(void)rememberAction
{
    self.rememberButton.selected = !self.rememberButton.selected;
    if (self.rememberButton.selected) {
        [[KAppConfig sharedConfig] setRememberPassword:YES];
    }else{
        [[KAppConfig sharedConfig] setRememberPassword:NO];
    }
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self.loginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.bottom.mas_equalTo(self.accountTf.mas_top).offset(-46);
        make.width.mas_equalTo(self.view);
        make.height.mas_equalTo(36);
    }];
    [self.accountTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.bottom.mas_equalTo(self.view.mas_centerY).offset(-80);
        make.height.mas_equalTo(30);
    }];
    [self.accLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(0.5);
        make.top.mas_equalTo(self.accountTf.mas_bottom);
    }];
    [self.passwordTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.accountTf.mas_left);
        make.right.mas_equalTo(self.accountTf.mas_right);
        make.height.mas_equalTo(self.accountTf.mas_height);
        make.top.mas_equalTo(self.accountTf.mas_bottom).offset(30);
    }];
    [self.pasLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(0.5);
        make.top.mas_equalTo(self.passwordTf.mas_bottom);
    }];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(self.pasLine.mas_bottom).offset(40);
        make.height.mas_equalTo(44);
    }];
    [self.rememberButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.loginButton.mas_left);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(10);
    }];
    [self.rememberText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.rememberButton.mas_right).offset(5);
        make.height.mas_equalTo(self.rememberButton.height);
        make.top.mas_equalTo(self.rememberButton.mas_top);
        make.right.mas_equalTo(140);
    }];
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.loginButton.mas_right);
        make.width.mas_equalTo(160);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(10);
    }];
    [self.forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(160);
        make.height.mas_equalTo(30);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-10);
    }];
    [self.view sendSubviewToBack:self.backgroundView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LazyLoad
-(UILabel *)loginLabel
{
    if (!_loginLabel) {
        _loginLabel = [[UILabel alloc]init];
        _loginLabel.text = @"Sign In";
        [_loginLabel sizeToFit];
        _loginLabel.textAlignment = NSTextAlignmentCenter;
        _loginLabel.textColor = [UIColor whiteColor];
        _loginLabel.font = [UIFont boldSystemFontOfSize:32];
        [self.view addSubview:_loginLabel];
    }
    return _loginLabel;
}

-(UITextField *)accountTf
{
    if (!_accountTf) {
        _accountTf = [[UITextField alloc]init];
        _accountTf.textColor = [UIColor whiteColor];
        _accountTf.tintColor = [UIColor whiteColor];
        _accountTf.borderStyle = UITextBorderStyleNone;
        _accountTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        _accountTf.keyboardType = UIKeyboardTypeEmailAddress;
        _accountTf.attributedPlaceholder = [self attributeText:@"Phone/Email" color:[UIColor whiteColor] font:[UIFont systemFontOfSize:16]];
        [self.view addSubview:_accountTf];
    }
    return _accountTf;
}

-(UITextField *)passwordTf
{
    if (!_passwordTf) {
        _passwordTf = [[UITextField alloc]init];
        _passwordTf.borderStyle = UITextBorderStyleNone;
        _passwordTf.tintColor = [UIColor whiteColor];
        _passwordTf.textColor = [UIColor whiteColor];
        _passwordTf.secureTextEntry = YES;
        _passwordTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        _passwordTf.keyboardType = UIKeyboardTypeAlphabet;
        _passwordTf.attributedPlaceholder = [self attributeText:@"Password" color:[UIColor whiteColor] font:[UIFont systemFontOfSize:16]];
        [self.view addSubview:_passwordTf];
    }
    return _passwordTf;
}

-(UIView *)accLine
{
    if (!_accLine) {
        _accLine = [self whiteLine];
    }
    return _accLine;
}

-(UIView *)pasLine
{
    if (!_pasLine) {
        _pasLine = [self whiteLine];
        [self.view bringSubviewToFront:_pasLine];
    }
    return _pasLine;
}

-(UIView*)whiteLine{
    UIView* view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    return view;
}

-(UIImageView *)backgroundView
{
    if (!_backgroundView) {
        _backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_back"]];
        _backgroundView.contentMode = UIViewContentModeScaleToFill;
        [self.view addSubview:_backgroundView];
    }
    return _backgroundView;
}

-(NSMutableAttributedString*)attributeText:(NSString*)text color:(UIColor*)color font:(UIFont*)font
{
    NSMutableAttributedString* attributeText = [[NSMutableAttributedString alloc]initWithString:text];
    [attributeText addAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:color} range:NSMakeRange(0, text.length)];
    return attributeText;
}

-(UIButton *)loginButton
{
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginButton setTitle:@"Sign In" forState:UIControlStateNormal];
        _loginButton.layer.cornerRadius = 20;
        _loginButton.backgroundColor = [UIColor whiteColor];
        [_loginButton setTitleColor:[UIColor colorWithHexString:KButtonTextColor] forState:UIControlStateNormal];
        @weakify(self);
        [_loginButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            [weak_self loginAction];
        }];
        [self.view addSubview:_loginButton];
    }
    return _loginButton;
}

-(UIButton *)rememberButton
{
    if (!_rememberButton) {
        _rememberButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rememberButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_rememberButton setImage:[UIImage imageNamed:@"unselect"] forState:UIControlStateNormal];
        [_rememberButton setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
        _rememberButton.backgroundColor = [UIColor clearColor];
        [_rememberButton addTarget:self action:@selector(rememberAction) forControlEvents:UIControlEventTouchUpInside];
        _rememberButton.size = CGSizeMake(24, 24);
        [self.view addSubview:_rememberButton];
    }
    return _rememberButton;
}

-(UILabel *)rememberText
{
    if (!_rememberText) {
        _rememberText = [UILabel new];
        _rememberText.text = @"Remember me";
        _rememberText.textColor = [UIColor whiteColor];
        _rememberText.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
        _rememberText.userInteractionEnabled = YES;
        [_rememberText addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rememberAction)]];
        [self.view addSubview:_rememberText];
    }
    return _rememberText;
}

-(UIButton *)registerButton
{
    if (!_registerButton) {
        _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerButton setTitle:@"Register" forState:UIControlStateNormal];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
        _registerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _registerButton.backgroundColor = [UIColor clearColor];
        [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        @weakify(self);
        [_registerButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            KRegisterViewController* vc = [KRegisterViewController new];
            [weak_self.navigationController pushViewController:vc animated:YES];
        }];
        [self.view addSubview:_registerButton];
    }
    return _registerButton;
}

-(UIButton *)forgetButton
{
    if (!_forgetButton) {
        _forgetButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_forgetButton setTitle:@"Forgot Password?" forState:UIControlStateNormal];
        _forgetButton.titleLabel.font = [UIFont systemFontOfSize:16];
        _forgetButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _forgetButton.backgroundColor = [UIColor clearColor];
        [_forgetButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        @weakify(self);
        [_forgetButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            KForgotViewController* vc = [KForgotViewController new];
            [weak_self.navigationController pushViewController:vc animated:YES];
        }];
        [self.view addSubview:_forgetButton];
    }
    return _forgetButton;
}

@end
